package userrole

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	v1 "ruoyi-vue-pro-go/api/userrole/v1"
	"ruoyi-vue-pro-go/internal/dao"
	"ruoyi-vue-pro-go/internal/model/do"
	"ruoyi-vue-pro-go/internal/service"
)

type (
	sUserRole struct{}
)

func init() {
	service.RegisterUserRole(New())
}

func New() service.IUserRole {
	return &sUserRole{}
}

func (s *sUserRole) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {
	res = &v1.GetListRes{}
	err = dao.SystemUserRole.Ctx(ctx).Scan(&res.List)
	return
}

func (s *sUserRole) GetListByUserId(ctx context.Context, req *v1.GetListByUserIdReq) (res *v1.GetListByUserIdRes, err error) {
	res = &v1.GetListByUserIdRes{}
	err = dao.SystemUserRole.Ctx(ctx).Where(do.SystemUserRole{
		UserId: req.UserId,
	}).Scan(&res.List)
	for _, item := range res.List {
		res.Ids = append(res.Ids, item.RoleId)
	}
	return
}

func (s *sUserRole) AssignUserRole(ctx context.Context, req *v1.AssignUserRoleReq) (res *v1.AssignUserRoleRes, err error) {
	res = &v1.AssignUserRoleRes{}
	r := ghttp.RequestFromCtx(ctx)
	tenantId := gconv.Int64(r.Header.Get("Tenant-Id"))
	roleIds := req.RoleIds
	// 先删除用户的所有角色(软删除)
	_, err = dao.SystemUserRole.Ctx(ctx).Where(do.SystemUserRole{
		UserId: req.UserId,
	}).Delete()
	if err != nil {
		g.Log().Error(ctx, err)
		return
	}
	for _, roleId := range roleIds {
		_, err = dao.SystemUserRole.Ctx(ctx).OnConflict("user_id, role_id").Save(do.SystemUserRole{
			UserId:   req.UserId,
			RoleId:   roleId,
			Deleted:  false,
			TenantId: tenantId,
		})
	}
	return
}
